package com.software.loginregister.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import com.software.loginregister.LoginActivity;
import com.software.loginregister.R;
import com.software.loginregister.api.UserHealthApi;
import com.software.loginregister.entity.Result;
import com.software.loginregister.entity.UserDetail;
import com.software.loginregister.util.RetrofitClient;
import com.software.loginregister.util.SharedPreferencesUtil;

public class HealthActivity extends AppCompatActivity {

    private TextView textHeight, textWeight, textBmi, textBmiStatus;
    private TextView textTaste, textAllergen, textDietaryRestrictions;
    private TextView textHealthAdvice;
    private Button buttonEdit;
    private static final String TAG = "HealthActivity";
    private SwipeRefreshLayout swipeRefresh;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_health);

        // 首先检查登录状态
        if (!SharedPreferencesUtil.isLoggedIn(this)) {
            Log.d(TAG, "用户未登录");
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, LoginActivity.class));
            finish();
            return;
        }

        Long userId = SharedPreferencesUtil.getUserId(this);
        Log.d(TAG, "当前登录用户ID: " + userId);

        initViews();
        setStatusBar();
        setupSwipeRefresh();
        loadData();

        buttonEdit.setOnClickListener(v -> {
            Intent intent = new Intent(HealthActivity.this, HealthEditActivity.class);
            startActivity(intent);
        });
    }

    private void initViews() {
        textHeight = findViewById(R.id.textHeight);
        textWeight = findViewById(R.id.textWeight);
        textBmi = findViewById(R.id.textBmi);
        textBmiStatus = findViewById(R.id.textBmiStatus);
        textTaste = findViewById(R.id.textTaste);
        textAllergen = findViewById(R.id.textAllergen);
        textDietaryRestrictions = findViewById(R.id.textDietaryRestrictions);
        textHealthAdvice = findViewById(R.id.textHealthAdvice);
        buttonEdit = findViewById(R.id.buttonEdit);
        swipeRefresh = findViewById(R.id.swipeRefresh);
    }
    private void setStatusBar() {
        Window window = getWindow();
        // 设置状态栏背景为透明
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(Color.TRANSPARENT);

        // 设置状态栏文字颜色为深色
        View decorView = window.getDecorView();
        int flags = decorView.getSystemUiVisibility();
        flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        decorView.setSystemUiVisibility(flags);

    }

    private boolean checkLoginStatus() {
        if (!SharedPreferencesUtil.isLoggedIn(this)) {
            Log.d(TAG, "用户未登录");
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, LoginActivity.class));
            finish();
            return false;
        }
        return true;
    }

    private void setupSwipeRefresh() {
        swipeRefresh.setColorSchemeResources(R.color.theme_color);
        swipeRefresh.setOnRefreshListener(this::loadData);
    }

    private void loadData() {
        // 先加载本地数据
        loadLocalHealthData();
        // 再请求网络数据
        fetchNetworkData();
    }

    private void fetchNetworkData() {
        Long userId = SharedPreferencesUtil.getUserId(this);
        if (userId == -1) {
            handleError("请重新登录");
            return;
        }

        RetrofitClient.getInstance()
                .create(UserHealthApi.class)
                .getUserHealth(userId)
                .enqueue(new Callback<Result<UserDetail>>() {
                    @Override
                    public void onResponse(Call<Result<UserDetail>> call,
                                           Response<Result<UserDetail>> response) {
                        swipeRefresh.setRefreshing(false);

                        if (!response.isSuccessful() || response.body() == null) {
                            handleError("数据加载失败");
                            return;
                        }

                        Result<UserDetail> result = response.body();
                        if (result.getCode() != 1 || result.getData() == null) {
                            handleError(result.getMsg());
                            return;
                        }

                        saveUserHealthData(result.getData());
                        updateUi(result.getData());
                    }

                    @Override
                    public void onFailure(Call<Result<UserDetail>> call, Throwable t) {
                        swipeRefresh.setRefreshing(false);
                        handleError("网络连接失败: " + t.getMessage());
                    }
                });
    }

    private void updateUi(UserDetail userDetail) {
        // 添加空值检查
        textHeight.setText(String.format("身高：%.1f cm",
                userDetail.getHeight() != null ? userDetail.getHeight() : 0.0));
        textWeight.setText(String.format("体重：%.1f kg",
                userDetail.getWeight() != null ? userDetail.getWeight() : 0.0));
        textBmi.setText(String.format("BMI：%.1f",
                userDetail.getBmi() != null ? userDetail.getBmi() : 0.0));
        textBmiStatus.setText(String.format("BMI状态：%s",
                userDetail.getBmiStatus() != null ? userDetail.getBmiStatus() : "未知"));
        textTaste.setText(String.format("口味偏好：%s",
                userDetail.getTaste() != null ? userDetail.getTaste() : "未设置"));
        textAllergen.setText(String.format("过敏原：%s",
                userDetail.getAllergen() != null ? userDetail.getAllergen() : "无"));
        textDietaryRestrictions.setText(String.format("饮食禁忌：%s",
                userDetail.getDietaryRestrictions() != null ? userDetail.getDietaryRestrictions() : "无"));
        textHealthAdvice.setText(userDetail.getHealthAdvice() != null ?
                userDetail.getHealthAdvice() : "暂无建议");
    }

    private void saveUserHealthData(UserDetail userDetail) {
        SharedPreferences prefs = getSharedPreferences("user_health", MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();

        // 添加空值检查，使用默认值 0.0
        editor.putFloat("height", userDetail.getHeight() != null ?
                userDetail.getHeight().floatValue() : 0f);
        editor.putFloat("weight", userDetail.getWeight() != null ?
                userDetail.getWeight().floatValue() : 0f);
        editor.putFloat("bmi", userDetail.getBmi() != null ?
                userDetail.getBmi().floatValue() : 0f);
        editor.putString("bmi_status", userDetail.getBmiStatus() != null ?
                userDetail.getBmiStatus() : "");
        editor.putString("taste", userDetail.getTaste() != null ?
                userDetail.getTaste() : "");
        editor.putString("allergen", userDetail.getAllergen() != null ?
                userDetail.getAllergen() : "");
        editor.putString("dietary_restrictions", userDetail.getDietaryRestrictions() != null ?
                userDetail.getDietaryRestrictions() : "");
        editor.putString("health_advice", userDetail.getHealthAdvice() != null ?
                userDetail.getHealthAdvice() : "");

        editor.apply();
    }
    private void loadLocalHealthData() {
        SharedPreferences prefs = getSharedPreferences("user_health", MODE_PRIVATE);

        UserDetail localData = new UserDetail();
        // 将 float 转换为 Double
        localData.setHeight(Double.valueOf(prefs.getFloat("height", 0f)));
        localData.setWeight(Double.valueOf(prefs.getFloat("weight", 0f)));
        localData.setBmi(Double.valueOf(prefs.getFloat("bmi", 0f)));
        localData.setBmiStatus(prefs.getString("bmi_status", ""));
        localData.setTaste(prefs.getString("taste", ""));
        localData.setAllergen(prefs.getString("allergen", ""));
        localData.setDietaryRestrictions(prefs.getString("dietary_restrictions", ""));
        localData.setHealthAdvice(prefs.getString("health_advice", ""));

        // 如果有本地数据，则先显示
        if (localData.getHeight() != null && localData.getHeight() > 0) {
            updateUi(localData);
        }
    }

    private void handleError(String message) {
        swipeRefresh.setRefreshing(false);
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
        if (message.contains("请重新登录")) {
            startActivity(new Intent(this, LoginActivity.class));
            finish();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadData();
    }
}